from stgapp.models import *
from django.http import HttpResponse, JsonResponse
import json


## 收益概览
def detail_incomeStatistics(request):
    """
    从summary表中读取收益统计信息
    """
    btc = TBackrun
    sr = TBacksummary
    data = ""
    id = request.POST.get("stgid")
    batchid = request.POST.get("batchid")
    date_dict = request.POST.get("date_obj")
    date_dict = json.loads(date_dict)
    start_date = date_dict.get("startdate")
    end_date = date_dict.get("endate")
    StgID = id
    ## 轮询，每次都去数据库查出batchid最大的记录，即最新的记录
    ## 首先查询run表中是否有记录
    if btc.objects.using("BackTestDB").filter(stgid=StgID).exists():
        backObj = btc.objects.using("BackTestDB").filter(stgid=StgID).values().order_by("-batchid").first()
        # backObj = btc.find_one({'StgID': StgID, 'BatchID': BatchID})
        if sr.objects.using("BackTestDB").filter(stgid=backObj['stgid'], batchid=batchid).exists():
            ## 轮询，每次都去数据库查出batchid最大的记录，即最新的记录
            item = sr.objects.using("BackTestDB").filter(stgid=backObj["stgid"], batchid=batchid).values().order_by("-batchid").first()
            # item = sr.find_one({'StrategyID': backObj['StgID'], 'BacktestID': backObj['BatchID']})
            obj = {
                "annual_return": round(float(item['annualret']) * 100, 3),
                "total_return": round(float(item['pl']) * 100, 3),
                "max_draw_down": round(float(item['maxdrawndown']) * 100, 3),
                "annual_volatility": round(float(item['annualvolatility']), 4),
                "sharpe_ratio": round(float(item['sharpratio']), 4),
                "calmar_ratio": round(float(item['calmarratio']), 4),
                "stability_of_time_series": round(float(item['stabilityoftimeseries']), 4),
                "omega_ratio": round(float(item['omegaratio']), 4),
                "sortino_ratio": round(float(item['sortinoratio']), 4),
                "start_date": item['simstartdate'],
                "end_date": item['simenddate'],
            }
            data = obj
        else:
            obj = {
                "annual_return": "",
                "total_return": "",
                "max_draw_down": "",
                "annual_volatility": "",
                "sharpe_ratio": "",
                "calmar_ratio": "",
                "stability_of_time_series": "",
                "omega_ratio": "",
                "sortino_ratio": "",
                "start_date": "",
                "end_date": "",
            }
            data = obj
    else:
        obj = {
            "annual_return": "",
            "total_return": "",
            "max_draw_down": "",
            "annual_volatility": "",
            "sharpe_ratio": "",
            "calmar_ratio": "",
            "stability_of_time_series": "",
            "omega_ratio": "",
            "sortino_ratio": "",
            "start_date": "",
            "end_date": "",
        }
        data = obj
    return JsonResponse(data, safe=False)


## 净值曲线
def detail_cumulativereturns(request):
    """
    从return表中获取数据，用于渲染ECharts净值曲线
    """
    id = request.POST.get("stgid")
    batchid = request.POST.get("batchid")
    btc = TBackrun
    rc = TBackreturn
    data = ""
    # sim_run表中的_id在return表中找不到
    StgID = id
    # BatchID = int(id.split('__')[1])
    backObj = btc.objects.using("BackTestDB").filter(stgid=StgID, batchid=batchid).values().first()
    if backObj is None:
        data = {
            'retDate': [],
            'retData': []
        }
        return JsonResponse(data, safe=False)
    if rc.objects.using("BackTestDB").filter(stgid=backObj['stgid'], batchid=batchid).exists():
        if rc.objects.using("BackTestDB").filter(stgid=backObj['stgid'], batchid=batchid).values().count() != 0:
            # if rc.find({'strategy_id': backObj['StgID'], 'BacktestID': backObj['BatchID']}).count() != 0:
            returnObj = rc.objects.using("BackTestDB").filter(stgid=backObj["stgid"], batchid=batchid).values().first()
            # returnObj = rc.find_one({'strategy_id': backObj['StgID'], 'BacktestID': backObj['BatchID']})
            retDate = str(returnObj['date']).strip("[").rstrip("]").rstrip(',').split(',')
            retData = returnObj['data'].strip('[').rstrip(']').rstrip(',').split(',')
            retDateList = []
            retDataList = []
            for item in retDate:
                retDateList.append(item.replace("\'", ''))
            for item in retData:
                retDataList.append(round(float(item.replace("\'", '')), 5))
            data = {
                'retDate': retDateList,
                'retData': retDataList
            }
    return JsonResponse(data, safe=False)
